﻿#include"XQCoding.h"
#include<QTextCodec>
#include<QDebug>
#include<iostream>
const std::string XQCoding::Utf8ToGbk(const std::string& str)
{
    QTextCodec* utf8 = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForLocale(utf8);
    //QTextCodec::setCodecForCStrings(utf8);
    QTextCodec* gbk = QTextCodec::codecForName("gbk");
    //1. utf8 -> unicode
    QString strUnicode = utf8->toUnicode(str.c_str());
    //2. unicode -> gbk, 得到QByteArray
    QByteArray gb_bytes = gbk->fromUnicode(strUnicode);
    std::string out = gb_bytes.data(); //获取其char *
	return out;
}

QByteArray XQCoding::Utf8ToGbk(const QByteArray& str)
{
    QTextCodec* utf8 = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForLocale(utf8);
    //QTextCodec::setCodecForCStrings(utf8);
    QTextCodec* gbk = QTextCodec::codecForName("gbk");
    //1. utf8 -> unicode
    QString strUnicode = utf8->toUnicode(str);
    //2. unicode -> gbk, 得到QByteArray
    QByteArray gb_bytes = gbk->fromUnicode(strUnicode);
    return gb_bytes;
}

const std::string XQCoding::GbkToUtf8(const std::string& str)
{
   // std::cout << str;
    QTextCodec* utf8 = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForLocale(utf8);
    //QTextCodec::setCodecForCStrings(utf8);
    QTextCodec* gbk = QTextCodec::codecForName("gbk");

    //gbk -> utf8
    //1. gbk to unicode
   auto strUnicode = gbk->toUnicode(str.c_str());
    //2. unicode -> utf-8
    QByteArray utf8_bytes = utf8->fromUnicode(strUnicode);
    std::string out = utf8_bytes.data(); //获取其char *
    return out;
}

QByteArray XQCoding::GbkToUtf8(const QByteArray& str)
{
    QTextCodec* utf8 = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForLocale(utf8);
    //QTextCodec::setCodecForCStrings(utf8);
    QTextCodec* gbk = QTextCodec::codecForName("gbk");

    //gbk -> utf8
    //1. gbk to unicode
    auto strUnicode = gbk->toUnicode(str);
    //2. unicode -> utf-8
    QByteArray utf8_bytes = utf8->fromUnicode(strUnicode);
    return utf8_bytes;
}

